package com.hnkywl.sts.service.sys;

import com.hnkywl.sts.dao.sys.KhjwhDao;
import com.hnkywl.sts.entity.sys.Khjwh;
import com.hnkywl.sts.util.BaseUtils;
import net.ruixin.orm.hibernate.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: ccr
 * Date: 13-5-20
 * Time: 下午7:40
 * To change this template use File | Settings | File Templates.
 */
@Service
public class KhjwhService {

    private KhjwhDao khjwhDao;

    @Transactional
    public String findAllKhjwhList(String pmName, Date start, Date endDate, int pageNo, int pageSize) {
        Page<Khjwh> khjPage = this.khjwhDao.findAllKhjwhList(pmName, start, endDate, pageNo, pageSize);
        List<Khjwh> khjList = khjPage.getResult() == null ? new ArrayList<Khjwh>() : khjPage.getResult();
        String khjJson = BaseUtils.fetchCollectionToJson(khjList, "id", "pm.name", "khj", "drrq", "dateCreated", "lastUpdated", "mj.qc");
        return "{\"total\":" + khjPage.getTotalCount() + ",\"rows\":[" + khjJson + "]}";
    }

    @Transactional
    public void saveOrUpdateKhj(List<Khjwh> khjList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String strDate = sdf.format(new Date());
        for (Khjwh khj : khjList) {
            String selHql = " from Khjwh where to_char(drrq,'yyyyMMdd') = ? and pm.id = ? ";
            List<Khjwh> kList = this.khjwhDao.find(selHql, strDate, khj.getPm().getId());
            if (null != kList && kList.size() > 0) {
                Khjwh khjT = kList.get(0);
                khjT.setKhj(khj.getKhj());
                khjT.setLastUpdated(khj.getLastUpdated());
                this.khjwhDao.save(khjT);
            } else {
                this.khjwhDao.save(khj);
            }
        }
    }


    @Transactional
    public Khjwh saveKhj(Long khjId, String khj) {
        Khjwh k = khjwhDao.get(khjId);
        k.setKhj(Double.parseDouble(khj));
        k.setLastUpdated(new Date());
        this.khjwhDao.save(k);
        return k;
    }

    @Autowired
    public void setKhjwhDao(KhjwhDao khjwhDao) {
        this.khjwhDao = khjwhDao;
    }
}
